package com.remotephone.capture

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.util.Log
import android.view.PixelCopy
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.remotephone.capture.ui.theme.CaptureTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream

class MainActivity : ComponentActivity() {
    private var transparentOverlay: View? = null
    private var opaqueOverlay: View? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            CaptureTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(
                        name = "Android",
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
    }

    override fun onResume() {
        super.onResume();
        checkOverlayPermissionAndAddOverlays();
    }

    override fun onDestroy() {
        super.onDestroy()
        removeOverlays()
    }

    private fun checkOverlayPermissionAndAddOverlays() {
        if (Settings.canDrawOverlays(this)) {
            addOverlays()
        } else {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:$packageName")
            )
            startActivityForResult(intent, REQUEST_OVERLAY_PERMISSION)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_OVERLAY_PERMISSION) {
            if (Settings.canDrawOverlays(this)) {
                addOverlays()
            } else {
                Toast.makeText(this, "悬浮窗权限未授予，无法添加遮罩", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun addOverlays() {
        if (isFinishing || isDestroyed) return

        val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager

        // 透明遮罩
        transparentOverlay = View(this).apply {
            setBackgroundColor(Color.TRANSPARENT)
        }
        val transparentParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )
        windowManager.addView(transparentOverlay, transparentParams)

        // 半透明遮罩
        opaqueOverlay = View(this).apply {
            setBackgroundColor(Color.argb(200, 0, 0, 0))
        }
        val opaqueParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )
        windowManager.addView(opaqueOverlay, opaqueParams)

        // 延迟截图
        CoroutineScope(Dispatchers.Main).launch {
            window.decorView.postDelayed({
                captureScreenshot(window.decorView)
            }, 1000)
        }
    }

    private fun removeOverlays() {
        val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
        transparentOverlay?.let { windowManager.removeView(it) }
        opaqueOverlay?.let { windowManager.removeView(it) }
        transparentOverlay = null
        opaqueOverlay = null
    }

    private fun captureScreenshot(view: View) {
        val width = view.width
        val height = view.height
        if (width == 0 || height == 0) {
            Log.e("Screenshot", "View 未初始化，无法截图")
            return
        }
        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        PixelCopy.request(window, bitmap, { result ->
            if (result == PixelCopy.SUCCESS) {
                Log.d("Screenshot", "截图成功：${bitmap.width}x${bitmap.height}")
                // 保存或处理截图
                saveBitmapToInternalStorage(bitmap, "capture.png")
            } else {
                Log.e("Screenshot", "截图失败：$result")
            }
        }, Handler(mainLooper))
    }

    fun saveBitmapToInternalStorage(bitmap: Bitmap, filename: String) {
        val file = File(this.filesDir, filename)
        try {
            // 使用 use 函数来确保流在完成后被正确关闭
            FileOutputStream(file).use { fos ->
                if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)) {
                    Log.d("SaveImage", "Bitmap saved successfully to ${file.absolutePath}")
                } else {
                    Log.e("SaveImage", "Failed to compress bitmap.")
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e("SaveImage", "Error saving bitmap to internal storage: ${e.message}")
        }
    }

    companion object {
        private const val REQUEST_OVERLAY_PERMISSION = 1234
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(text = "Hello $name!", modifier = modifier)
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    CaptureTheme {
        Greeting("Android")
    }
}
